#pragma once

#include "iconfiguration_provider.h"
#include <QObject>
#include <QString>
#include <QFileSystemWatcher>
#include <QJsonArray>
#include <QJsonObject>
#include <QTimer>
#include <QMutex>
#include <QDateTime>
#include <memory>

namespace infrastructure {

/**
 * @class JsonFileProvider
 * @brief 从JSON文件提供配置的提供者，支持热重载
 */
class JsonFileProvider : public QObject, public IConfigurationProvider {
    Q_OBJECT

public:
    explicit JsonFileProvider(const QString& filePath, int priority = 100);
    virtual ~JsonFileProvider();

    // IConfigurationProvider interface
    ConfigurationData load() override;
    bool isAvailable() const override;
    QString getDescription() const override;
    void setChangeCallback(ConfigurationChangeCallback callback) override;
    void startWatching() override;
    void stopWatching() override;
    int getPriority() const override;

    // JsonFileProvider 特有的方法
    QString getFilePath() const { return m_filePath; }
    void setReloadDelay(int milliseconds) { m_reloadDelay = milliseconds; }
    QJsonObject getJsonObject() const;
    
    // 写入功能
    bool writeToFile(const QHash<QString, QVariant>& data);
    bool updateValue(const QString& key, const QVariant& value);
    bool removeValue(const QString& key);
    bool saveData(const ConfigurationData& data);

private slots:
    void onFileChanged(const QString& path);
    void onReloadTimer();

private:
    QString m_filePath;
    int m_priority;
    int m_reloadDelay;  // 重新加载延迟，避免频繁重载
    bool m_watching;
    mutable QMutex m_mutex;
    
    std::unique_ptr<QFileSystemWatcher> m_watcher;
    std::unique_ptr<QTimer> m_reloadTimer;
    ConfigurationChangeCallback m_callback;
    ConfigurationData m_lastData;
    
    ConfigurationData loadFromFile();
    QJsonObject getJsonObjectInternal() const;  // 新增：内部使用，不加锁
    void parseJsonObject(const QJsonObject& obj, const QString& prefix, QHash<QString, QVariant>& result);
    QJsonObject createJsonObject(const QHash<QString, QVariant>& data);
    void setJsonValue(QJsonObject& obj, const QString& key, const QVariant& value);
    void setJsonValueRecursive(QJsonObject& obj, const QStringList& keyParts, int index, const QVariant& value);  // 新增
    bool fileExists() const;
    QDateTime getLastModified() const;
    bool createDirectoryIfNeeded() const;
};

} // namespace infrastructure 